package yunquan.wang.jbpm5.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.jbpm.task.service.UserGroupCallback;

public class JdbcUserGroupCallback implements UserGroupCallback {

	private static  Map<String, Set<String>> userGroups=new HashMap<String,Set<String>>();
	private static Set<String> groupNames=new HashSet<String>();

	@Override
	public boolean existsUser(String userId) {
		checkInit();
		return userGroups.containsKey(userId);
	}

	@Override
	public boolean existsGroup(String groupId) {
		checkInit();
		return groupNames.contains(groupId);
	}

	@Override
	public List<String> getGroupsForUser(String userId, List<String> groupIds,
			List<String> allExistingGroupIds) {
		checkInit();
 
		return new ArrayList(userGroups.get(userId));
	}

	public static List<String> getuserGroups(String userName)
	{
		new JdbcUserGroupCallback().checkInit();
		return new ArrayList(userGroups.get(userName));
	}
	
	/**
	 * 初始化数据
	 */
	private void checkInit() {
		if (groupNames.size()==0) {
		List<Map<String,Object>> groups=	JdbcUtils.query("SELECT	name,groupname  FROM a_user u LEFT JOIN a_usergroup ug ON ug.userid=u.id LEFT JOIN a_group g ON g.id=ug.groupid");
		for(Map<String,Object> single:groups)
		{
		String groupName=	single.get("groupname").toString();
		String username=single.get("name").toString();
			groupNames.add(groupName);
			 Set<String> usergroupinfo=	userGroups.get(username);
			 if(usergroupinfo==null)
			 {
				 usergroupinfo=new HashSet<String>();
				 userGroups.put(username, usergroupinfo);
			 }
			 usergroupinfo.add(groupName);
		}
	}
}
 
}
